package com.unisyou.controller;

import com.unisyou.bean.WXUsersBean;
import com.unisyou.config.PropertiesConfig;
import com.unisyou.utils.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Autowired
    private HttpClient httpClient;
    @Autowired
    private PropertiesConfig propertiesConfig;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取验证码
     * @return
     */
    @PostMapping("/getVerifyCode")
    public R getVerifyCode(@RequestBody String mobile){
        String url = propertiesConfig.getUrl()+propertiesConfig.getCodePath();
        String param = JSONUtils.stringToJsonByFastjson("userName",mobile);
        log.info("请求接口为:{},参数为:{}",url,param);
        Map<String,Object> resultMap = httpClient.clientForPostBody(url,param);
        if("0".equals(resultMap.get("resultCode").toString())){
            Map<String, Object> resultData = JSONUtils.jsonToMap(resultMap.get("resultData").toString());
            log.info("请求成功,该{}手机号码的验证码为{}",mobile,resultData.get("code"));
            return R.ok();
        }else{
            String reasonMsg = resultMap.get("resultMsg").toString();
            log.info("请求失败,原因为:{}",reasonMsg);
            return R.error(-1, reasonMsg);
        }
    }

    /**
     * 校验手机和验证码
     * @param paramsMap
     * @return
     */
    @RequestMapping("/verifyCode")
    public R verifyCode(@RequestBody Map<String,Object> paramsMap, HttpServletRequest request
        ,HttpServletResponse response) throws WxErrorException {
        paramsMap.put("type",2); //1：注册  2：登陆  3：找回密码
        String mobile = paramsMap.get("userName").toString();
        String url = propertiesConfig.getUrl()+propertiesConfig.getVerifyCodePath();
        String beanToJSONString = JSONUtils.beanToJson(paramsMap);
       //Map<String,Object> verifyParamsMap = SignDecode.getInstance().encode(beanToJSONString);
        Map<String,Object> resultMap = httpClient.clientForPostBody(url, beanToJSONString);
        if ("0".equals(resultMap.get("resultCode").toString())) {
            String openid = String.valueOf(CookieUtil.get(request,"openid").getValue());
            Map<String, Object> resultData = JSONUtils.jsonToMap(resultMap.get("resultData").toString());
            String token = resultData.get("token").toString();
            //修改用户手机号码
            String updateUrl = propertiesConfig.getUrl()+propertiesConfig.getSaveWxUserInfoPath();
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openid);
            WXUsersBean wxUsersBean = WXUsersBean.transfer(wxMpUser);
            wxUsersBean.setMobile(mobile);
            beanToJSONString = JSONUtils.beanToJson(wxUsersBean);
            Map<String,Object> updateParamsMap = SignDecode.getInstance().encode(beanToJSONString);
            paramsMap.put("token","");
            Map<String,Object> updateResultMap = httpClient.clientForPostBody(updateUrl,updateParamsMap);
            if(!"0".equals(updateResultMap.get("resultCode").toString())){
                log.info("修改用户手机号码失败:{}",updateResultMap.get("resultMsg").toString());
            }
            CookieUtil.set(response,"mobile",mobile,365*60*60*24);
            CookieUtil.set(response,"token",token,365*60*60*24);
            stringRedisTemplate.opsForValue().set(mobile,token);
            return R.ok();
        }
        log.info("手机号码验证失败:{}",resultMap.get("resultMsg"));
        return R.error(-1,resultMap.get("resultMsg").toString());
    }
}
